import store from "./factory";
// var sha256 = require('./sha256two.js');
import sha256 from './sha256two';
import {config} from "../api/config";

/**
 *
 * getGwsignConfig("invitation/advertise/tips?name='xiaohong'", {lat: 29.8172, lng: 121.547}) -> {gwsign: "9859f669663fa98bb3c416e175aa8eeae495eabae145ef0aef2d804e8d9086fe", t: 1594200692880, s: "vdrKwIsd2"}
 * @param gwsign:  sha256 加密后的参数  (规则: sha256(path + timestamp + (key + salt) + params))   http://wiki6.xlgxapp.com/pages/viewpage.action?pageId=18517656
 * @param t: 时间戳
 * @param s: 从登陆接口中拿到的salt
 * @param urlParamsObj 从url中提取出来的params参数对象  因为有些请求的参数既在data的body中传又在url的params中传 要整合到一起 // {name: "'xiaohong'"}
 * @param deleteParamsUrl  剔除了params后的url    // "invitation/advertise/tips"
 * @param paramsData  整合了url和data中的参数, 其中data中的sign要剔除   // {name: "'xiaohong'", lat: 29.8172, lng: 121.547}
 */

export const getGwsignConfig = (url = '', data = {}) => {
    let urlParamsObj = {},deleteParamsUrl = ''
    if (url.includes('?')) {
        urlParamsObj = getUrlParams(url)
        deleteParamsUrl = url.split("?")[0]
    } else {
        deleteParamsUrl = url
    }
    let paramsData = data ? JSON.parse(JSON.stringify(data)) : {}
    // 如果参数写在path上面, 一并和到body中 如果body中有sign这个字段, 把他剔除
    paramsData = Object.assign({}, urlParamsObj, paramsData)
    delete paramsData.sign
    const saltConfig = {
        salt: store.get('gwsSalt') ? (config.gwsignKey + store.get('gwsSalt')) : config.gwsignKey,
        path: deleteParamsUrl,
        timestamp: store.get('differenceTime') ? (new Date().getTime()+store.get('differenceTime')) : new Date().getTime(),
        params: json2params(paramsData)
    }
    const gwsign = '/'+saltConfig.path+saltConfig.timestamp+saltConfig.salt+saltConfig.params
    // console.log(gwsign, 'gwsign')
    let sha256Sig = sha256.sha256_digest(gwsign)
    // console.log(sha256Sig, 'sha256Sig')
    const gwsignConfig = {
        'gwsign': sha256Sig,
        't': saltConfig.timestamp,
        's': saltConfig.salt.replace(config.gwsignKey, "")
    }
    return gwsignConfig
}

// console.log(getGwsignConfig("invitation/advertise/tips?name='xiaohong'", {lat: 29.8172, lng: 121.547}), 'xs')
/**
 * 将json转化为params格式
 * {coord: 0, lat: 29.8172, lng: 121.547, la: '', name: '小明', Name: '小红', areaid: 31500} -> coord=0&lat=29.8172&lng=121.547&name=小红
 * jsonArray:  去除为空的值 (0和false要保留)     // ["coord", "lat", "lng", "name", "Name", "areaid"]
 * paramsArray:  按字母排序的 数组              // ["areaid", "coord", "lat", "lng", "name", "Name"]
 * noRepetitionParamsArray  将paramsArray数组剔除了重复值(不区分大小写),重复的值取最后一位   // ["areaid", "coord", "lat", "lng", "Name"]
 */
// json2params({coord: 0, lat: 29.8172, lng: 121.547, la: '', name: '小明', Name: '小红', areaid: 31500})
function json2params(json, slice = '&') {
    if (json) {
        let jsonArray = []
        // 为空的值就不需要传过去了
        for(let key in json) {
            if (typeof json[key] == 'boolean' || typeof json[key] == 'number') {
                jsonArray.push(key)
            } else {
                if (json[key]) {
                    jsonArray.push(key)
                }
            }
        }
        let paramsArray = jsonArray.sort(function (a,b) {
            // 字符串比较实用localeCompare  中文比较localeCompare(b,'zh-CN')
            return a.localeCompare(b)
        })
        // 为了处理这样的情况 有几个接口会出现  {areaid: 312, areaId: 312, areaID: 312} 取最后一个
        let noRepetitionParamsArray = JSON.parse(JSON.stringify(paramsArray))
        for(let i = 0; i< paramsArray.length; i++) {
            for(let j= i+1; j < paramsArray.length; j++) {
                if (paramsArray[i].toLocaleLowerCase()==paramsArray[j].toLocaleLowerCase()) {
                    noRepetitionParamsArray.splice(i,1)
                }
            }
        }
        return noRepetitionParamsArray
            .reduce((acc, item) => {
                // 参数为数组对象的时候去除头尾的"", 里面的保持原样  exp -> /rider/api/v3/settlement/paySettlement1594087605594V0e0BP3seorders=[{"orderNo":"R299884148671884960","feeType":"RIDING_FEE"}]&settlementSource=ARREARS
                if (typeof json[item] == 'object') {
                    return (String(acc) + item + '=' + JSON.stringify(json[item]).replace(/(^"*)|("*$)/g, "") + slice);
                } else {
                    return (String(acc) + item + '=' + json[item] + slice);
                }

            }, '')
            .slice(0, -1);
    } else {
        return ""
    }
}

/**
 * 获取url的params值, 转化为对象
 * exp : https://testermapi.xlgxapp.com/user/api/v2/troubleType?feedbackType=REPORT -> {feedbackType: REPORT}
 */
function getUrlParams(url) {
    let paramsObj = {}
    let paramsArray
    paramsArray = url.split("?")[1].split("&")
    paramsArray.map(v => paramsObj[v.split("=")[0]] = v.split("=")[1])
    return paramsObj
}

export const isUrlHasNull = (url="") => {
    let hasNull = false
    if (url.includes('/null')) {
        hasNull = true
    } else {
        hasNull = false
    }
    return hasNull
}

export const bodyHasNullOrUndefined = (json) => {
    let hasNullOrUndefined = false
    if (json) {
        for(let key in json) {
            if (typeof json[key] == 'undefined' || json[key] == null) {
                hasNullOrUndefined = true
                break;
            } else {
                hasNullOrUndefined = false
            }
        }
    }
    return hasNullOrUndefined
}

//undefined 过滤器
export const undefinedFifter = (str) => {
    if (!str) {
        return false
    }
    if (JSON.stringify(str).includes("undefined") || JSON.stringify(str).includes("Undefined")) {
        return false
    } else {
        return str
    }
}

